package com.cml.learn.netty.client;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class TimeClient {
	public static void main(String[] args) throws Exception {
		EventLoopGroup workerGroup = new NioEventLoopGroup();

		try {
			Bootstrap b = new Bootstrap(); // (1)
			b.group(workerGroup); // (2)
			b.channel(NioSocketChannel.class); // (3)
			b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
			b.handler(new ChannelInitializer<SocketChannel>() {
				@Override
				public void initChannel(SocketChannel ch) throws Exception {
					System.out.println("client init channel ");
					ChannelPipeline pipeline = ch.pipeline();
					pipeline.addLast("stringD", new StringDecoder());
					pipeline.addLast("stringC", new StringEncoder());
					pipeline.addLast("http", new HttpClientCodec());
					pipeline.addLast("chat", new TimeClientHandler());
				}
			});

			// Start the client.
			ChannelFuture f = b.connect("127.0.0.1", 8080).sync(); // (5)
			f.addListener(new ChannelFutureListener() {

				public void operationComplete(ChannelFuture future) throws Exception {
					System.out.println("client operationComplete=>" + future.isSuccess());
					if (!future.isSuccess()) {
						future.cause().printStackTrace();
					}
				}
			});
			Channel channel = f.channel();
			while (true) {
				BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
				String input = reader.readLine();
				if (input != null) {
					if ("quit".equals(input)) {
						System.exit(1);
					}
					channel.writeAndFlush(input);
				}
			}

			// Wait until the connection is closed.
			// f.channel().closeFuture().sync();
		} finally {
			workerGroup.shutdownGracefully();
		}
	}
}